<template>
  <div class="app-container">
    <el-form label-width="120px">
      <el-form-item label="讲师名称">
        <el-input v-model="teacher.name" />
      </el-form-item>
      <el-form-item label="讲师排序">
        <el-input-number v-model="teacher.sort"
                         controls-position="right"
                         :min="0" />
      </el-form-item>
      <el-form-item label="讲师头衔">
        <el-select v-model="teacher.level"
                   clearable
                   placeholder="请选择">
          <!--数据类型一定要和取出的json中的一致，否则没法回填

                因此，这里value使用动态绑定的值，保证其数据类型是number
                -->
          <el-option :value="1"
                     label="高级讲师" />
          <el-option :value="2"
                     label="首席讲师" />
        </el-select>
      </el-form-item>
      <el-form-item label="讲师资历">
        <el-input v-model="teacher.career" />
      </el-form-item>
      <el-form-item label="讲师简介">
        <el-input v-model="teacher.intro"
                  :rows="10"
                  type="textarea" />
      </el-form-item>
      <!-- 讲师头像：TODO -->
      <!-- action="http://10.18.19.18:9001/eduoss/fileoss" -->
      <el-form-item label="讲师头像">
        <el-upload class="avatar-uploader"
                   :action="BASE_API+'/eduoss/fileoss'"
                   :show-file-list="false"
                   :on-success="handleAvatarSuccess"
                   :before-upload="beforeAvatarUpload">
          <img v-if="teacher.avatar"
               :src="teacher.avatar"
               class="avatar">
          <i v-else
             class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button :disabled="saveBtnDisabled"
                   type="primary"
                   @click="saveOrUpdate">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import teacher from '@/api/edu/teacher'

const defaultForm = {
  name: '',
  sort: 0,
  level: '',
  career: '',
  intro: '',
  avatar: ''
}

export default {
  data() {
    return {
      teacher: defaultForm,
      saveBtnDisabled: false,
      BASE_API: process.env.VUE_APP_BASE_API

    }
  },
  // 路由导航切换时，如果两个路由渲染同一个组件，组件会被重用。组件的声明周期钩子函数create不会被调用，组件一些数据无法根据path的改变而得到更新
  // 监听路由的变化
  watch: {
    $route(to, from) {
      this.init()
    }
  },
  created() {
    this.init()
  },
  methods: {
    saveOrUpdate() {
      this.saveBtnDisabled = true
      if (!this.teacher.id) {
        this.saveData()
      } else {
        this.updateData()
      }
    },
    saveData() {
      teacher.save(this.teacher).then(res => {
        return this.$message({
          type: 'success',
          message: '保存成功'
        })
      }).then(res => {
        this.$router.push({
          path: '/edu/teacher'
        })
      }).catch(reject => {
        this.$message({
          type: 'error',
          message: '保存失败'
        })
      })
    },
    // 获取教师信息
    fetchDataById(id) {
      teacher.getById(id).then(response => {
        console.log(response.data.item.avatar)
        this.teacher = response.data.item
      }).catch((res) => {
        this.$message({ type: 'error', message: '获取数据失败' })
      })
    },
    // 更新id信息
    updateData() {
      this.saveBtnDisabled = true
      teacher.updateById(this.teacher).then(res => {
        console.log(this.teacher)
        console.log(this.teacher.avatar)
        return this.$message({
          type: 'success',
          message: '修改成功'
        })
      }).then(res => {
        this.$router.push({
          path: '/edu/teacher'
        })
      }).catch((res) => {
        this.$message({
          type: 'error',
          message: '保存失败'
        })
      })
    },
    // 初始化函数
    init() {
      if (this.$route.params && this.$route.params.id) {
        const id = this.$route.params.id
        this.fetchDataById(id)
      } else {
        this.teacher = { ...defaultForm }
      }
    },
    // 处理头像上传
    handleAvatarSuccess(res, file) {
      this.teacher.avatar = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
